<?php
session_start();
//Check if logged in. Redirect to login if not.
if(!isset($_SESSION['loggedIn'])){
	header('Location: StudentLogin.php');
}
//Set timezone for timestamp. Grab all important information
date_default_timezone_set("America/New_York");
$file = $_FILES['file']['name'];
$class = $_SESSION['class'];
$student=$_SESSION['student'];
$assign = $_POST['assign'];
$message=$_POST['MessageTextArea'];
$name = substr($file, strlen($file)-4);
//Check if file extension is .zip. If not, display error.
if(strcmp($name,".zip") != 0){
	echo "<br/>Error! Filetype is not a zipfile! <br />";
}else{
//Set filename to User_Assignment_Timestamp.zip
//Set student version to Assignment_Timestamp.zip
//Log the upload
	$timestamp=date('m-d-Y_h-i-s_a', time());
	$ip=$_SERVER['REMOTE_ADDR'];
	$filename = $_POST['assign'] . "_" . $_SESSION['student'] . "_" . $timestamp . ".zip";
	$_FILES['file']['name']=$filename;
	$copyname = $_POST['assign'] . "_" . $timestamp . ".zip";
	$uploadLoc="../data/Classes/" . $_SESSION['class'] . "/Assignments/" . $_POST['assign'] ."/" . $filename;
	$copyLoc="../data/Classes/" . $_SESSION['class'] . "/Students/" . $_SESSION['student'] . "/" . $copyname;
	move_uploaded_file($_FILES['file']['tmp_name'],$uploadLoc);
	copy($uploadLoc,$copyLoc);
	$message=nl2br($message);
	$log="../data/Logs/upload_log.txt";
	$str=$timestamp . ", " . $class . ", " . $student . ", " . $assign . ", ";
	file_put_contents($log, $str . "\n", FILE_APPEND);
	//If message field isn't blank, log the message in the appropriate file, and 
	//log the message upload
	if(strcmp($message,"") != 0){
		$log="../data/Logs/message_log.txt";
		file_put_contents($log,$str . "\n",FILE_APPEND);
		$store="../data/Classes/" . $class . "/messages.txt";
		$msginfo=$timestamp . "_" . $student . "_" . $assign . "_" . $ip . "\n" . $message . "\n\n";
		file_put_contents($store,$msginfo,FILE_APPEND);
	}
	echo $file . " has been uploaded successfully!";
}
?>
<html>
<br />
<a href="StudentAssignment.php">Go back</a>
</html>